<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Validation\ValidationException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use App\Tools\Common;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * 报告或记录异常
     *
     * 这是一个向 Sentry、Bugsnag 等外部服务发送异常信息的好位置
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
     */
    public function render($request, Exception $exception)
    {

        // if (method_exists($exception, 'getStatusCode')) {
        //     return response(['ServerTime' => time(), 'ServerNo' => 404, 'ResultData' => '404']);
        // }

        if (env('WX_WORK_ENABLED', true)) {

            // 消息队列 体验更加
            $webhook = env('WX_WORK_PATH');
            $time = date('Y-m-d H:i:s');
            $serverUrl = $_SERVER['HTTP_HOST']; // 服务器域名
            $clientIp = $request->getClientIp(); // 使用$request 获取客户端ip
            $params = json_encode($request->all());

            $data = [
                "msgtype" =>  "markdown",
                "markdown" => [
                    "content" => "
                    > 服务地址: <font color='info'> {$serverUrl}</font>
                    > 请求IP: <font color='info'> {$clientIp}</font>
                    > 请求方式: <font color='info'> {$request->method()}</font>
                    > 请求路径: <font color='info'> {$request->path()}</font>
                    > 请求参数: <font color='warning'> {$params}</font>
                    > 报错文件: <font color='comment'> {$exception->getFile()}</font>
                    > 错误行数: <font color='comment'> {$exception->getLine()}</font>
                    > 报错信息: `{$exception->getMessage()}`
                    > 报错时间: <font color='info'> {$time}</font>"
                ]
            ];

            $data_string = json_encode($data);

            Common::curl($webhook, $data_string);
        }
        return parent::render($request, $exception);
    }

    /**
     * 定义默认的环境变量
     *
     * @return array
     */
    // protected function context()
    // {
    //     return array_merge(parent::context(), [
    //         'foo' => 'bar',
    //     ]);
    // }

}
